﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：RabbitMqMessagePublisher.cs
// 功能描述：TongTongMall.RabbitMq
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Commanding.Messaging;
using TongTongMall.Util.Etc;

namespace TongTongMall.RabbitMq.RabbitMq
{
    public class RabbitMqMessagePublisher : DisposableObject, IMessagePublisher
    {
        private readonly string exchangeName;
        private readonly IConnection connection;
        private readonly IModel channel;
        private bool disposed;


        protected RabbitMqMessagePublisher(string uri, string exchangeName)
        {
            this.exchangeName = exchangeName;
            var factory = new ConnectionFactory() { Uri = uri };
            this.connection = factory.CreateConnection();
            this.channel = connection.CreateModel();
        }

        /// <summary>
        /// 发送到rabbitMq消息
        /// </summary>
        /// <typeparam name="TMessage"></typeparam>
        /// <param name="message"></param>
        public void PublishMessage<TMessage>(TMessage message)
        {
            channel.ExchangeDeclare(exchange: this.exchangeName, type: "fanout");
            var properties = channel.CreateBasicProperties();
            //消息持久化
            properties.DeliveryMode = 2;
            var json = JsonConvert.SerializeObject(message, Formatting.Indented);
            var bytes = Encoding.UTF8.GetBytes(json);


            channel.BasicPublish(exchange: this.exchangeName, routingKey: "", basicProperties: null, body: bytes);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!disposed)
                {
                    this.channel.Dispose();
                    this.connection.Dispose();
                    disposed = true;
                }
            }
        }

    }
}
